
import { initSearchConfig, TableSearchPanel, XxAliOssUploadModal, XxpageContainer, XxTable } from "@/ui";
import React, { useContext, useEffect, useRef, useState } from "react";
import { imageLibraryApi as api } from "@/api";
import { Context, globalModal } from "@/data";
import {
    DeleteOutlined,
    CopyOutlined
} from '@ant-design/icons';
import styles from "./src/styles/index.module.scss"
import { Button, Select, Space, TreeSelect, Tree, Image, Typography, Spin, Form, Input, message, Checkbox, Tooltip } from "antd";
import { WenjianjiaIcon, GerenIcon, CloseIcon, FuzhiIcon, DeleteIcon } from "@/assets/icon";
import Notfound from "@/ui/notFound/not-found";

const TreeTitleNode = ({ item, getDir = Function }) => {
    const { modal } = useContext(Context);
    const onDeleteDir = () => {
        modal.confirm({
            title: "删除目录将删除此目录下所有资源，确定要这么操作吗？",
            centered: true,
            onOk: async () => {
                console.log("删除目录", item);
                try {
                    await api.deleteDir({ prefix: item.key });
                    getDir();
                } catch (error) {

                }
            },
        });
    }

    return <div className="tree-customer-title">

        <div className="name" >{item.title}</div>
        <div className="closeBtn"
            onClick={() => onDeleteDir(item)}
        >
            <CloseIcon />
        </div>
    </div>
}




/**@description 【ImageLibrary图库】页面 */
const ImageLibrary = ({ type = "page", images = [] }) => {
    const { modal } = useContext(Context);
    /**预览相关 */
    const [visible, setVisible] = useState(false);
    const [previewImage, setPreviewImage] = useState(null);
    const [sourceTreeData, setSourceTreeData] = useState([]);


    const [selectedImgs, setSelectedImgs] = useState([]); //当前选中的图片IDs
    const [params, setParams] = useState(null)
    const [form] = Form.useForm();
    const uploadRef = useRef(null);
    const [dirTree, setDirTree] = useState([]);
    const [loadingDir, setLoadingDir] = useState(true);
    const [loadingDelete, setLoadingDelete] = useState(false);
    const [loadingImages, setLoadingImages] = useState(true);
    const [selectedKeys, setSelectedKeys] = useState(null);
    const editFormRef = useRef(null); //用于引用编辑表单的 ref 对象
    const [state, setState] = useState({
        data: [],
        dirTree: [{
            children: []
        }],
        totalCount: 0,
        nextContinuationToken: null,
        isTruncated: false,//是否还有更多？
    })




    useEffect(() => {
        if (params) {
            getList(params)
        }
    }, [params])



    //加载目录树
    const getDir = async () => {
        try {
            setLoadingDir(true);
            const { data, code, msg } = await api.queryDir({
                dir: 'images/'
            });
            setDirTree(addIconsToTreeData(data));
            setSourceTreeData(data);
            //重置参数
            setParams({
                pageSize: 70,
                prefix: data[0].name,
                currentToken: null
            })
            setNextTokens([null]);
        } catch (error) {

        } finally {
            setLoadingDir(false)
        }
    }

    useEffect(() => {
        getDir()
    }, [])

    const [nextTokens, setNextTokens] = useState([]);
    const [index, setIndex] = useState(0);
    //点击下一页
    const onChangePage = (type) => {
        if (type === "up") {
            const key = index - 1;
            setParams({
                ...params,
                currentToken: nextTokens[key] || null
            })
            setIndex(key)
        } else {
            //下一页
            const key = index + 1;
            setParams({
                ...params,
                currentToken: nextTokens[key]
            })
            setIndex(key)

        }

    }

    /**@description 查找列表 */
    const getList = async ({ pageSize, prefix, currentToken = null } = params) => {
        setLoadingImages(true);
        const { data, code, msg } = await api.queryList({
            pageSize: pageSize,
            prefix: prefix,
            nextContinuationToken: currentToken,
        });
        setState({
            isTruncated: data.isTruncated,
            data: [...data.list],
            totalCount: data.totalCount || 0,
            nextContinuationToken: data.nextContinuationToken || null,
        })
        setSelectedImgs([]);
        // 如果还有下一页，则将下一个分页标记加入到pageTokens中，以便下一次加载更多数据
        setNextTokens([...nextTokens, data.nextContinuationToken || null]);

        setLoadingImages(false);
    }



    const addIconsToTreeData = (treeData) => {
        return treeData.map(item => {
            // 深拷贝当前节点，避免修改原始数据
            const newNode = { ...item, };
            // newNode.title = judgmentTitle(item)

            // 判断是否有子节点且子节点数量大于0
            if (item.children && item.children.length > 0) {
                // 分组节点使用TeamOutlined图标
                newNode.icon = <WenjianjiaIcon />;
                // 递归处理子节点
                newNode.children = addIconsToTreeData(item.children);
            } else {
                // 叶子节点使用UserOutlined图标
                newNode.icon = <WenjianjiaIcon />;
            }
            newNode.title = TreeTitleNode({ item, getDir });
            //判断节点是否在selectedKyes中，在的话，返回带有勾选框的节点

            return newNode;

        });
    }



    //点击树节点
    const onSelectTree = (selectedKeys, e) => {
        setSelectedKeys(selectedKeys[0]);
        setParams({
            pageSize: 70,
            prefix: selectedKeys[0],
            currentToken: null
        })
        setNextTokens([null]);
        setIndex(0)
    }


    //删除一个对象
    const onDeleteObject = async ({ name = String }) => {
        try {
            modal.confirm({
                title: "确认删除所选的图片吗？",
                content: "这将永久删除所选图片，请谨慎操作。",
                centered: true,
                onOk: async () => {
                    try {
                        await api.deleteObject({ name });
                    } catch (error) {

                    } finally {
                        setParams({
                            pageSize: 70,
                            prefix: selectedKeys && selectedKeys[0] || "images/",
                            currentToken: null
                        })
                    }
                },
            });
        } catch (error) {

        }
    }


    //新建目录

    const addDir = () => {
        modal.confirm({
            title: "新建目录",
            centered: true,
            content: (
                <div>
                    <Form ref={editFormRef} form={form}>
                        <Form.Item rules={[{ required: true, message: '请选择上级目录位置' }]} name="parentDir" label="上级目录">
                            <TreeSelect
                                loading={loadingDir}
                                treeData={[
                                    {
                                        title: "图库",
                                        key: 'images/',
                                        children: sourceTreeData

                                    }
                                ]}
                                fieldNames={{
                                    label: 'title',
                                    value: 'key',
                                    title: 'title',

                                }}
                            />
                        </Form.Item>
                        <Form.Item label="目录名称" name="dirName">
                            <Input placeholder="请输入目录名" />
                        </Form.Item>
                    </Form>
                </div>
            ),
            onOk: async () => {
                try {
                    const { dirName, parentDir } = await editFormRef.current.validateFields();
                    await api.createDir({
                        dirName, parentDir
                    });
                    form.resetFields();
                } catch (error) {

                } finally {
                    getDir();

                }
            },
            onCancel: () => {
                editFormRef.current.resetFields();
            },
        });


    }

    //点击弹出上传
    const onClickUpload = () => {
        uploadRef.current.open()
    }



    //选择图片
    const onSelectImage = (name) => {
        const result = selectedImgs.includes(name) === true ? false : true;
        // console.log(record)
        if (result === true) {
            setSelectedImgs([...selectedImgs, name]);
            console.log("选择的图片 ", [...selectedImgs, name]);
            let list = ([...selectedImgs, name]).map(item => ({
                type: "image",
                src: "https://static.bigkel.com" + item,
                href: "https://static.bigkel.com" + item,
                alt: new Date().getTime(),
                style: {},
                children: [
                    {
                        text: ""
                    }
                ]
            }))
            console.log("选择的图片 ", list)
            images = list;
        } else {
            setSelectedImgs(selectedImgs.filter((item) => item !== name));
            console.log("选择的图片 ", selectedImgs.filter((item) => item !== name))
            let list = (selectedImgs.filter((item) => item !== name)).map(item => ({
                type: "image",
                src: "https://static.bigkel.com/" + item,
                href: "https://static.bigkel.com/" + item,
                alt: new Date().getTime(),
                style: {},
                children: [
                    {
                        text: ""
                    }
                ]
            }))
            console.log("选择的图片 ", list)
            images = list;
        }
    }


    /**
     * 将文本复制到剪贴板
     *
     * @param {string} text - 需要复制的文本
     * @returns {Promise<void>} 无返回值，使用Promise处理异步操作
     */
    const copyToClipboard = async (text) => {
        try {
            await navigator.clipboard.writeText(text);
            message.success('复制成功');  // 使用antd的message组件显示成功消息
        } catch (err) {
            console.error('无法复制文本: ', err);
        }
    };

    //批量删除所选图片
    const onDeleteSelectedImages = () => {
        modal.confirm({
            title: "确认删除所选的图片吗？",
            content: "这将永久删除所选图片，请谨慎操作。",
            centered: true,
            onOk: async (close) => {
                setLoadingDelete(true);
                for (let i = 0; i < selectedImgs.length; i++) {
                    try {
                        await api.deleteObject({ name: selectedImgs[i] });
                    } catch (error) {

                    } finally {


                    }
                }
                console.log("遍历 删除完了", selectedKeys)
                setParams({
                    pageSize: 70,
                    prefix: selectedKeys && selectedKeys[0] || "images/",
                    currentToken: null
                })

                setSelectedImgs([]);
                setLoadingDelete(false);
                close();
            },
        });
    }

    return (
        <XxpageContainer defaultStyle={{
            padding: 0,
            backgroundColor: "#fff",
            minHeight: "100%",
            height: "100%",
            display: "flex",
            flexDirection: "column",
        }}>
            <XxAliOssUploadModal
                dirTree={dirTree}
                onRef={uploadRef}
                onUploadSuccess={getList}
                accept=".jpg,.png,.icon,.jpeg,.gif,.bmp,.tiff,.psd,.svg,.webp,.avif,.mp4,.mov,.wmv,.flv,.mkv,.avi,.mp3,.wav,.m4a,.aac,.flac,.oga,.opus,.webm,.ogg,"
            />
            <div className={styles.pages}>
                <div className="header-action">
                    <div className="select-bucket">
                        {
                            selectedImgs.length > 0 ? (
                                <>
                                    <Space>
                                        <Button type="primary" onClick={() => setSelectedImgs(state.data.map(item => item.name))}>全选</Button>
                                        <span>已选择{selectedImgs.length}个文件</span>
                                    </Space>
                                </>
                            ) : <Button type="primary" onClick={() => addDir()}>新建目录</Button>
                        }
                    </div>
                    <div className="button-action">
                        <Space align="right">
                            {
                                selectedImgs.length > 0 ? (
                                    <>

                                        <Button loading={loadingDelete} type="primary" danger onClick={() => onDeleteSelectedImages()}>删除</Button>
                                        <Button type="primary" onClick={() => setSelectedImgs([])} >取消</Button>
                                    </>
                                ) : <Button type="primary" onClick={onClickUpload}>上传图片</Button>
                            }

                        </Space>
                    </div>
                </div>
                <div className="center">
                    <div className="left-cate">
                        <Spin spinning={loadingDir}>
                            <div className="cate-list">
                                <Tree
                                    defaultSelectedKeys={selectedKeys ? [selectedKeys] : []}
                                    className={styles.cateStyle}
                                    showIcon={true}
                                    treeData={dirTree}
                                    onSelect={onSelectTree}
                                />
                            </div>
                        </Spin>
                    </div>
                    <div className="right-image-container">
                        <div className="image-list">
                            <Spin spinning={loadingImages}>
                                {
                                    state.data.length === 0 &&
                                    <div className="empty-container">
                                        <Notfound description={false} />
                                    </div>
                                }
                                {/* 图片列表 */}
                                <Image
                                    width={200}
                                    style={{ display: 'none' }}
                                    src={`${previewImage}?x-oss-process=image/blur,r_50,s_50/quality,q_1/resize,m_mfit,h_200,w_200`}
                                    preview={{
                                        visible,
                                        scaleStep: 0.5,
                                        src: previewImage,
                                        onVisibleChange: value => {
                                            setVisible(value);
                                        },
                                    }}
                                />
                                {
                                    state.data.length > 0 &&
                                    <div className="list-scroll">
                                        <div className="image-list-container">
                                            {
                                                state.data.map((item, key) => (
                                                    <div className="image-card" key={key}>
                                                        <div className="box">
                                                            <div className="image-container">
                                                                <Image
                                                                    preview={false}
                                                                    width={'100%'}
                                                                    src={item.url}
                                                                    className="img"
                                                                />
                                                                <div className="img-mask"
                                                                    style={{ display: selectedImgs.includes(item.name) && "block" }}
                                                                    onClick={() => {
                                                                        onSelectImage(item.name)
                                                                    }}
                                                                >
                                                                    <div className="mask-container"
                                                                        onDoubleClick={() => {
                                                                            setPreviewImage(item.url);
                                                                            setVisible(true);
                                                                        }}

                                                                    >
                                                                        <div className="header">
                                                                            <span className="check">
                                                                                <Checkbox
                                                                                    checked={selectedImgs.includes(item.name)}
                                                                                    onChange={(e) => {
                                                                                        console.log(e.target.checked);
                                                                                        onSelectImage(item.name)
                                                                                    }} />
                                                                            </span>
                                                                        </div>
                                                                        <div className="bottom">
                                                                            <div className="background"></div>
                                                                            <div className="action">
                                                                                <div className="space-container">
                                                                                    <Space>
                                                                                        <Tooltip title="复制图片地址">
                                                                                            <Button icon={<CopyOutlined />} type="link" onClick={(e) => { e.stopPropagation(); copyToClipboard(item.url) }} />
                                                                                        </Tooltip>
                                                                                        <Tooltip title="删除这张图片">
                                                                                            <Button icon={<DeleteOutlined />} type="link" onClick={(e) => {
                                                                                                e.stopPropagation();
                                                                                                onDeleteObject({ name: item.name })
                                                                                            }} />
                                                                                        </Tooltip>
                                                                                    </Space>

                                                                                </div>
                                                                            </div>

                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>

                                                    </div>
                                                ))
                                            }
                                        </div>
                                    </div>
                                }
                            </Spin>
                        </div>
                        {/* 分页 */}
                        <div className="page-container">
                            <Space>
                                <Button
                                    disabled={params?.currentToken == null ? true : false}
                                    onClick={() => {
                                        onChangePage("up")
                                    }}
                                >上一页</Button>
                                <Button
                                    disabled={state.isTruncated ? false : true}
                                    onClick={() => {
                                        onChangePage("next")
                                    }}
                                >下一页</Button>
                            </Space>
                        </div>

                    </div>
                </div>
            </div>

        </XxpageContainer>
    )
}

export default ImageLibrary;
